﻿var ComFunJS = new Object({
    FileAPI: "http://122.114.116.79:9000/document/fileupload",
    FilePathAPI: "http://122.114.116.79:9000/document/",
    setCookie: function (name, value) {
        var Days = 30;
        var exp = new Date();
        exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
        document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString();
    },
    getCookie: function (name) {
        var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");

        if (arr = document.cookie.match(reg))

            return unescape(arr[2]);
        else
            return null;
    },
    delCookie: function (name) {
        var exp = new Date();
        exp.setTime(exp.getTime() - 1);
        var cval = getCookie(name);
        if (cval != null)
            document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
    },
    getnowuser: function () {
        return ComFunJS.getCookie("username");
    },

    getRootPath: function () {
        //获取当前网址，如： http://localhost:8083/uimcardprj/share/meun.jsp
        var curWwwPath = window.document.location.href;
        //获取主机地址之后的目录，如： uimcardprj/share/meun.jsp
        var pathName = window.document.location.pathname;
        var pos = curWwwPath.indexOf(pathName);
        //获取主机地址，如： http://localhost:8083
        var localhostPaht = curWwwPath.substring(0, pos);
        //获取带"/"的项目名，如：/uimcardprj
        var projectName = pathName.substring(0, pathName.substr(1).indexOf('/') + 1);
        return (localhostPaht + projectName);
    },//获取路径
    DelItem: function (items, delkey, delval) {
        for (i = items.length - 1; i >= 0; i--) {
            if (items[i][delkey] == delval) {
                items.splice(i, 1)
            }
        }
    },//删除数据项

    FindItem: function (arrs, func) {
        var temp = [];
        for (var i = 0; i < arrs.length; i++) {
            if (func(arrs[i])) {
                temp[temp.length] = arrs[i];
            }
        }
        return temp;
    },
    getQueryString: function (name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]); return null;
    },//获取参数中数据
    convstr: function (str, len) {
        if (len) {
            return str.length > len ? str.substr(0, len) + "..." : str;
        }
        else {
            return str.length > 10 ? str.substr(0, 10) + "..." : str;
        }
    },//转字符串
    getnowdate: function (format) {
        var now = new Date();

        var year = now.getFullYear();       //年
        var month = now.getMonth() + 1;     //月
        var day = now.getDate();            //日
        var clock = year + "-";

        if (format == "yyyy-mm") {
            if (month < 10)
                clock += "0";
            clock += month + "-";
        }

        if (format == "yyyy-mm-dd") {
            if (month < 10)
                clock += "0";
            clock += month + "-";
            if (day < 10) {
                clock += "0";
            }
            clock += day + "-";
        }
        return (clock.substr(0, clock.length - 1));
    },//获取当前时间
    daysBetween: function (start, end) {
        var OneMonth = start.substring(5, start.lastIndexOf('-'));
        var OneDay = start.substring(start.length, start.lastIndexOf('-') + 1);
        var OneYear = start.substring(0, start.indexOf('-'));
        var TwoMonth = end.substring(5, end.lastIndexOf('-'));
        var TwoDay = end.substring(end.length, end.lastIndexOf('-') + 1);
        var TwoYear = end.substring(0, end.indexOf('-'));
        var cha = ((Date.parse(TwoMonth + '/' + TwoDay + '/' + TwoYear) - Date.parse(OneMonth + '/' + OneDay + '/' + OneYear)) / 86400000);
        return cha;
    },
    GetBMPeople: function (dom) {
        var checkvalue = dom.next('input:hidden').val();
        if (dom.data("people")) {
            checkvalue = dom.data("people").userid;
        }
        ComFunJS.winbtnwin("/View/Base/UserSelect.html?checkvalue=" + checkvalue, "选择人员", 900, 540, {}, function (layero, index) {
            var frameid = $("iframe", $(layero)).attr('id');
            var people = window.frames[frameid].getqiandaopeople();
            dom.data("people", people).val(people.username).next('input:hidden').val(people.userid);
            if (dom.is("td")) {
                dom.text(people.username);
            }
            layer.close(index)
        })
    },//选择人员
    GetBMPeopleTree: function (tip, $valdom) {


        $.ajax({
            type: "GET",
            url: ComFunJS.getRootPath() + "/Base/AdminHandle.ashx",
            dataType: "html",
            data: { "CheckNodes": $valdom.val(), "Action": "GetBranchUser" },
            beforeSend: function (XMLHttpRequest) {
                parent.MyDialog.Mytips();
            },
            success: function (msg) {
                var zNodes = null;
                var zTreeObj = null;
                var setting = {
                    data: {
                        simpleData: {
                            enable: true,
                            idKey: "id",
                            pIdKey: "pId",
                            rootPId: 0
                        }
                    },
                    check: {
                        enable: true,
                        chkStyle: "checkbox",
                        chkboxType: { "Y": "ps", "N": "ps" }
                    },
                    view: {
                        showLine: false
                    },
                    callback: {
                        onCheck: function (event, treeId, treeNode) {
                            var checknodes = zTreeObj.getCheckedNodes(true);
                            var s = "";
                            if (checknodes.length != 0) {
                                $.each(checknodes, function (i, n) {
                                    var check = (n && n.isUser == "Y");
                                    if (check) {
                                        s = s + n.id + ',';
                                    }
                                });
                                $valdom.val(s);
                            }
                        }
                    }
                };
                zNodes = eval(msg);
                zTreeObj = $.fn.zTree.init($(".ztree", tip), setting, zNodes);
            },
            complete: function (XMLHttpRequest, textStatus) {
                parent.MyDialog.CloseMytips();
            },
            error: function () {
            }
        });

    },//选择人员树
    convertuser: function (user) {
        var returnmsg = "";
        var arruser = user.split(",");
        if (user !== "") {
            if (parent.$("body").data("usersarr")) {
                var usersarr = parent.$("body").data("usersarr");
                for (var i = 0; i < arruser.length; i++) {
                    var rearr = ComFunJS.FindItem(usersarr, function (obj) {
                        return obj.UserName == arruser[i];
                    })
                    if (rearr.length > 0) {
                        returnmsg = returnmsg + "," + rearr[0].UserRealName;
                    }
                }
            } else {
                $.ajaxSettings.async = false;
                $.getJSON('/API/SZHLAPI.ashx?Action=GETUSERJS', { P1: "" }, function (resultData) {
                    if (resultData.ErrorMsg == "") {
                        var usersarr = resultData.Result;
                        for (var i = 0; i < arruser.length; i++) {
                            var rearr = ComFunJS.FindItem(usersarr, function (obj) {
                                return obj.UserName == arruser[i];
                            })
                            if (rearr.length > 0) {
                                returnmsg = returnmsg + "," + rearr[0].UserRealName;
                            }
                        }
                        parent.$("body").data("usersarr", usersarr);
                    }
                })

            }
        }
        if (returnmsg.length > 1) {
            returnmsg = returnmsg.substring(1);
        }
        return returnmsg;
    },
    converfilesize: function (size) {
        if (size) {
            var size = parseFloat(size);
            var rank = 0;
            var rankchar = 'Bytes';
            while (size > 1024) {
                size = size / 1024;
                rank++;
            }
            if (rank == 1) {
                rankchar = "KB";
            }
            else if (rank == 2) {
                rankchar = "MB";
            }
            else if (rank == 3) {
                rankchar = "GB";
            }
            return size.toFixed(2) + " " + rankchar;
        }
    
    },

    //弹出帮助函数
    winsuccess: function (content) {

        layer.msg(content || '操作成功。。', {
            icon: 6,
            offset: 0,
            shift: 6
        });

    },//成功窗口
    winsuccessnew: function (content) {
        layer.open({
            type: 1,
            title: false,
            closeBtn: false,
            shade: [0],
            area: ['340px', '50px'],
            offset: 'rb', //右下角弹出
            time: 2000, //2秒后自动关闭
            shift: 2,
            content: '<div class="sucalert">操作成功</div>', //iframe的url，no代表不显示滚动条
            end: function () { //此处用于演示
            }
        });

    },//成功窗口New
    winprompt: function (callbact) {
        layer.prompt(function (val) {
            callbact.call(this, val);
        });
    },

    winwarning: function (content) {
        layer.msg(content, {
            icon: 5,
            offset: 200,
            shift: 6
        });
    },//警告窗口
    wintips: function (content, callback) {
        layer.msg(content, {
            offset: 200,
            shift: 6
        });
    },//提示
    wintip: function (tip, dom) {
        layer.tips(tip, dom)
    },//提示
    winload: function () {
        layer.load();
    },//加载

    wincloseload: function () {

        layer.closeAll('loading');
    },//关闭加载
    winconfirm: function (title, yes, no) {
        layer.confirm(title, {
            btn: ['确认', '取消'], //按钮
            shade: false //不显示遮罩
        }, function () {
            layer.closeAll('dialog');
            return yes.call(this);
        }, function () {
            return no && no.call(this);
        });
    },//确认框
    winviewform: function (url, title, width, height, option) {
        var width = width || $("body").width() - 300;
        var height = height || $("#main").height();
        var optionwin = {
            type: 2,
            fix: false, //不固定
            area: [width + 'px', height + 'px'],
            maxmin: true,
            content: url,
            title: title,
            shadeClose: true //加上边框
        }
        layer.open(optionwin);
    },//普通查看网页窗口
    winviewformright: function (url, callbact) {
        var width = $("body").width() * 2 / 5;
        var height = $("#main").height() + 10;
        var optionwin = {
            type: 2,
            fix: false, //不固定
            area: [width + 'px', height + 'px'],
            offset: 'rb',
            content: url,
            title: false,
            shade: false,
            shift: 7,
            shadeClose: false,
            success: function () {
                $(".layui-layer-setwin").css("right", width + "px");
            },
            end: function () {
                if (callbact) {
                    return callbact.call(this);
                }
            }
        }
        return layer.open(optionwin);
    },
    winbtnwin: function (url, title, width, height, option, btcallbact) {
        var width = width || $("body").width() - 300;
        var height = height || $("#main").height();
        var optionwin = {
            type: 2,
            fix: false, //不固定
            area: [width + 'px', height + 'px'],
            maxmin: true,
            content: url,
            title: title,
            shadeClose: false,
            success: function (layero, index) {
                if ($(layero).find(".successfoot").length == 0) {
                    var footdv = $('<div class="layui-layer-title successfoot" style="border-bottom-width: 1px; padding: 0 20px 0 10px;margin-top: -3px;height:50px"></div>');
                    var btnConfirm = $("<a href='#' class='btn btn-sm btn-success' style='float:right; margin-top: 10px;width: 140px;'><i class='fa fa-spinner fa-spin' style='display:none'></i> 确   认</a>");
                    var btnCancel = $("<a href='#' class='btn btn-sm btn-danger' style='float:right; margin-top: 10px;margin-right: 10px;width: 80px;'>取  消</a>");

                    btnConfirm.appendTo(footdv).bind('click', function () {
                        return btcallbact.call(this, layero, index, btnConfirm);
                    })
                    btnCancel.appendTo(footdv).bind('click', function () {
                        layer.close(index)
                    })
                    $(layero).append(footdv);
                }

            }

        }
        layer.open(optionwin);
    },//带确认框的窗口
    winviewhtml: function (content, title, width, height, callbact) {
        var width = width || 600;
        var height = height || 400;
        layer.open({
            type: 1,
            title: title,
            skin: 'layui-layer-rim', //加上边框
            area: [width + 'px', height + 'px'],
            content: content,
            shadeClose: true,
            success: function (layero, index) {
                if (callbact) {
                    return callbact.call(this, layero, index);
                }
            }

        });
    },//加载HTML
    winold: function (url) {
        var iWidth = 610;                          //弹出窗口的宽度;
        var iHeight = 600;                       //弹出窗口的高度;
        //获得窗口的垂直位置
        var iTop = (window.screen.availHeight - 30 - iHeight) / 2;
        //获得窗口的水平位置
        var iLeft = (window.screen.availWidth - 10 - iWidth) / 2;
        var params = 'width=' + iWidth
                   + ',height=' + iHeight
                   + ',top=' + iTop
                   + ',left=' + iLeft
                   + ',channelmode=yes'//是否使用剧院模式显示窗口。默认为 no
                   + ',directories=yes'//是否添加目录按钮。默认为 yes
                   + ',fullscreen=no' //是否使用全屏模式显示浏览器
                   + ',location=no'//是否显示地址字段。默认是 yes
                   + ',menubar=no'//是否显示菜单栏。默认是 yes
                   + ',resizable=no'//窗口是否可调节尺寸。默认是 yes
                   + ',scrollbars=yes'//是否显示滚动条。默认是 yes
                   + ',status=yes'//是否添加状态栏。默认是 yes
                   + ',titlebar=yes'//默认是 yes
                   + ',toolbar=no'//默认是 yes
        ;
        window.open(url, name, params);
    },//老窗口
    initForm: function () {
        //时间
        //日期
        if ($(".szhl_form_date")[0]) {
            $(".szhl_form_date").datetimepicker({
                format: "yyyy-mm-dd"
            });
            $(".szhl_form_date").each(function () {
                if ($(this).val() === "" && !$(this).hasClass("null")) {
                    $(this).val(ComFunJS.getnowdate("yyyy-mm-dd"));
                }
                $(this).trigger('change')
            })
        }
        //年份
        if ($(".szhl_form_date_year")[0]) {
            $(".szhl_form_date_year").datetimepicker({
                minView: 4,
                startView: 4,
                format: "yyyy"
            })
            if ($(".szhl_form_date_year").val() === "") { $(".szhl_form_date_year").val(ComFunJS.getnowdate("yyyy")); }
            $(".szhl_form_date_year").trigger('change')
        }

        //月份
        if ($(".szhl_form_date_mon")[0]) {
            $(".szhl_form_date_mon").datetimepicker({
                minView: 3,
                startView: 3,
                format: "yyyy-mm"
            })
            if ($(".szhl_form_date_mon").val() === "") { $(".szhl_form_date_mon").val(ComFunJS.getnowdate("yyyy-mm")); }
            $(".szhl_form_date_mon").trigger('change')
        }

        //时间
        if ($(".szhl_form_date_time")[0]) {
            $(".szhl_form_date_time").datetimepicker({
                minView: 0,
                format: "yyyy-mm-dd hh:ii"
            });
        }
        if ($(".szhl_UEEDIT").length > 0) {
            $(".szhl_UEEDIT").each(function () {
                var input = $(this);
                var ubid = $(this).attr("id");
                var um = UM.getEditor(ubid);
                if ($(this).attr("umheight")) {
                    um.setHeight($(this).attr("umheight"));
                } else {
                    um.setHeight("150")
                }
                if (input.val() != "") {
                    um.ready(function () {
                        //需要ready后执行，否则可能报错
                        um.setContent(input.val());
                    })
                }
                um.addListener('contentChange', function () {
                    input.val(UM.getEditor(ubid).getContent())
                })


            })
        }
        // $('.szhl_getPeoples').bind('click', function () { ComFunJS.GetBMPeople($(this)) }).attr("onfocus", "this.blur()");
        if ($(".szhl_getPeoples:hidden").length > 0) {
            $(".szhl_getPeoples:hidden").each(function () {
                var $input = $(this);
                var issignle = $(this).attr("signle")?"Y" : "N";
                var panval = "";
                if ($input.val() != "") {
                    $.each($input.val().split(','), function (i, n) {
                        panval = panval + '<div class="pCard"><div class="pName">' + ComFunJS.convertuser(n) + '</div></div>';
                    });
                }
                var $panelsc = $('<div class="panel panel-default" style="margin-bottom: 0px;"><div class="panel-body">' + panval + '<input type="button" value="选择人员" class="btn btn-info btn-upload" /></div></div>')
                       .insertAfter($input);
                $panelsc.find('.btn-upload').bind('click', function () {
                    var $btnSel = $(this);
                    ComFunJS.winbtnwin("/View/Base/UserSelect.html?checkvalue=" + $input.val() + "&issignle=" + issignle, "选择人员", 900, 540, {}, function (layero, index) {
                        var frameid = $("iframe", $(layero)).attr('id');
                        var people = window.frames[frameid].getqiandaopeople();
                        $input.data("people", people).val(people.userid);
                        $btnSel.parent().find(".pCard").remove();
                        $.each(people.username.split(','), function (i, n) {
                            if (n != "") {
                                $('<div class="pCard"><div class="pName">' + n + '</div></div>').insertBefore($btnSel);
                            }
                        });
                        layer.close(index)
                    })
                })

            })
        }
        if ($(".szhl_Upload:hidden").length > 0) {
            $(".szhl_Upload:hidden").each(function () {
                var $input = $(this);
                var btnName = $(this).attr('title') ? $(this).attr('title') : "上传文件";//按钮名称
                var FileType = $(this).attr('FileType') ? $(this).attr('FileType') : "";//文件类型(pic代表图片)
                var $panelsc = $('<div class="panel panel-default" style="margin-bottom: 0px;"><div class="panel-body"><input type="button" value="' + btnName + '" class="btn btn-info btn-upload" /></div><ul class="list-group"></ul></div>')
                    .insertAfter($input);
                $panelsc.find('.btn-upload').bind('click', function () {
                    parent.ComFunJS.winbtnwin(ComFunJS.FileAPI, "上传", "700", "500", {}, function (layero, index, btdom) {
                        var fjids = "";
                        btdom.addClass("disabled").find("i").show();
                        var frameid = $("iframe", $(layero)).attr('id');
                        var nowwin = parent.window.frames[frameid].contentWindow;
                        nowwin.location = "/View/Base/Success.html?ID=3";//应用附件
                        var int = parent.window.setInterval("getwinname()", 1000);//循环等待,直到上传成功并返回文件数据
                        parent.window.getwinname = function () {
                            try {
                                if (nowwin.filedata) {
                                    parent.window.clearInterval(int)
                                    var fjdata = nowwin.filedata;
                                    btdom.removeClass("disabled").find("i").hide();
                                    btdom.unbind("click");
                                    btdom.one("click", function () {
                                        for (var i = 0; i < fjdata.length; i++) {
                                            var $fileitem = $("<a    class='list-group-item'   fileid='" + fjdata[i].ID + "' >" + fjdata[i].Name + "<span class='glyphicon glyphicon-download-alt'  fileid='" + fjdata[i].ID + "'  FileMD5='" + fjdata[i].FileMD5 + "'  style='margin-left: 5px;'></span><span class='glyphicon glyphicon-trash pull-right'></span></a>");
                                            $fileitem.find('.glyphicon-trash').bind('click', function () {
                                                $(this).parent().remove();
                                                var tempfjids = "";
                                                $panelsc.find('.list-group-item').each(function () {
                                                    tempfjids = tempfjids + $(this).attr("fileid") + ",";
                                                })
                                                if (tempfjids.length > 0) {
                                                    tempfjids = tempfjids.substring(0, tempfjids.length - 1)
                                                }
                                                $input.val(tempfjids);
                                            })
                                            $fileitem.find('.glyphicon-download-alt').bind('click', function () {
                                                window.open(ComFunJS.FilePathAPI + $(this).attr("FileMD5"));
                                            })

                                            $panelsc.find('.list-group').append($fileitem);
                                        }

                                        $panelsc.find('.list-group-item').each(function () {
                                            fjids = fjids + $(this).attr("fileid") + ",";
                                        })
                                        if (fjids.length > 0) {
                                            fjids = fjids.substring(0, fjids.length - 1)
                                        }
                                        $input.val(fjids);
                                        parent.layer.close(index);
                                    });
                                };
                            } catch (e) {
                            }
                        }


                    });
                })
                if ($input.val() != "") {
                    $.getJSON('/API/FTAPI.ashx?Action=GETFILESLIST', { P1: $input.val() }, function (data) {
                        if (data.ErrorMsg == "") {
                            var fjdata = data.Result;
                            for (var i = 0; i < fjdata.length; i++) {
                                var $fileitem = $("<a  class='list-group-item'   fileid='" + fjdata[i].ID + "' >" + fjdata[i].Name + "<span class='glyphicon glyphicon-download-alt' fileid='" + fjdata[i].ID + "' FileMD5='" + fjdata[i].FileMD5 + "' style='margin-left: 5px;'></span><span class='glyphicon glyphicon-trash pull-right'></span></a>");
                                $fileitem.find('.glyphicon-trash').bind('click', function () {
                                    $(this).parent().remove();
                                    var tempfjids = "";
                                    $panelsc.find('.list-group-item').each(function () {
                                        tempfjids = tempfjids + $(this).attr("fileid") + ",";
                                    })
                                    if (tempfjids.length > 0) {
                                        tempfjids = tempfjids.substring(0, tempfjids.length - 1)
                                    }
                                    $input.val(tempfjids);
                                })
                                $fileitem.find('.glyphicon-download-alt').bind('click', function () {
                                    window.open(ComFunJS.FilePathAPI + $(this).attr("FileMD5"));
                                })
                                $panelsc.find('.list-group').append($fileitem);
                            }
                            if ($input.attr("UploadType") == "1") {
                                $panelsc.find('.glyphicon-trash').remove();
                            }
                        }
                        else {
                            $panelsc.find('.panel-body').text("无附件");
                        }
                    });
                }
                if ($input.attr("UploadType") == "1") {
                    $panelsc.find('.btn-upload').remove();
                }

            })
        }
    },
    initsetajax: function () { /// 配置AJAX
        if (parent) {
            $(document).ajaxStart(function () {
                parent.ComFunJS.winload();
            }).ajaxSuccess(function (e, jqXHR, s, data) {
                try {
                    if (s.type == "POST") {
                         data = $.parseJSON(data)
                    }
                    if (data.ErrorMsg == "NOSESSION") {
                        alert("需要重新登陆");
                        return
                    }
                    if (data.ErrorMsg!="") {
                        parent.ComFunJS.winwarning(data.ErrorMsg)
                    }
                    parent.ComFunJS.wincloseload();
                } catch (e) {
                    parent.ComFunJS.wincloseload();
                }

            })
                .ajaxError(function (event, request, settings) {
                    //alert(request.status);
                    //alert(request.readyState);
                    //alert(settings);
                //parent.ComFunJS.wincloseload();
                //parent.ComFunJS.winwarning("悲剧了..网页出错了")
            });
        } else {
            $(document).ajaxStart(function () {
                ComFunJS.winload();
            }).ajaxSuccess(function (e, jqXHR, s, data) {
                try {
                    if (s.type == "POST") {
                        data = $.parseJSON(data)
                    }
                    if (data.ErrorMsg == "NOSESSION") {
                        alert("需要重新登陆")
                        return;
                    }
                    if (data.ErrorMsg != "") {
                        parent.ComFunJS.winwarning(data.ErrorMsg)
                    }
                    ComFunJS.wincloseload();
                } catch (e) {
                    ComFunJS.wincloseload();
                }

            })
            //.ajaxError(function (event, request, settings) {
            //    ComFunJS.wincloseload();
            //    ComFunJS.winwarning("悲剧了..网页出错了")
            //});
        }

    },
    getSPStatus: function (status, status1, isforbid) {
        if ((isforbid == "Y" && status1 == 1) || (isforbid == "N" && status == 1)) {
            content = '已审批';

        } else if (status1 == -1 || status == -1) {
            content = '已退回';
        } else {
            content = '<a href="#"> <i class="fa fa-cog fa-spin" style="margin-right:5px"></i>正在审批</a>';
        }
        return content;
    }
});
